//
//  PPAddTopicViewController.m
//  PetParadise
//
//  Created by 陈无忌 on 8/3/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPAddTopicViewController.h"
#import "PPKeyWordsTableViewController.h"
#import "PPKeyWordsCollectionViewCell.h"
#import "PPImageCell.h"
#import "supportingHeadFiles.h"
#import "PPCameraAuthorization.h"
#import "ELCImagePickerController.h"
#import "ELCImagePickerHeader.h"

@interface PPAddTopicViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,ELCImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UICollectionView *imageColletionView;
@property (weak, nonatomic) IBOutlet UICollectionView *keyWordCollectionView;


@property (weak, nonatomic) IBOutlet UITextView *topicContentTextView;
@property (weak, nonatomic) IBOutlet UILabel *msgLabel;
@property (weak, nonatomic) IBOutlet UIView *tagView;

@property (strong, nonatomic) NSMutableArray *pathstringArray;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (weak, nonatomic) PPSystemConfiguraton *config;
@property (nonatomic) int uploadCount;

@property (nonatomic, strong) NSMutableArray *keyWordArray;
@end

@implementation PPAddTopicViewController

- (NSMutableArray *)keyWordArray
{
    if (!_keyWordArray) {
        _keyWordArray = [NSMutableArray array];
    }
    return _keyWordArray;
}

-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        _imagePicker.allowsEditing = NO;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.keyWordCollectionView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.uploadCount = 0;
    self.imageColletionView.delegate = self;
    self.imageColletionView.dataSource = self;
    
    self.keyWordCollectionView.delegate = self;
    self.keyWordCollectionView.dataSource = self;
    
    self.topicContentTextView.delegate = self;
    
    self.pathstringArray = [[NSMutableArray alloc]init];
    [self.imageColletionView reloadData];
    
    self.tagView.layer.cornerRadius = 9.0;
    self.tagView.layer.borderWidth = 1.0;
    self.tagView.layer.borderColor = [UIColor colorWithRed:200.0/255.0 green:200.0/255.0 blue:200.0/255.0 alpha:1.0].CGColor;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Custom method
- (void)addPictureButton {
    if (self.imageArray.count <= 9) {
        UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                                 delegate:self
                                                        cancelButtonTitle:@"取消"
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:@"拍照", @"从相册中选取", nil];
        [choiceSheet showInView:self.view];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"最多只能发布九张图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
    }
}

-(void)deleteImage:(UIButton *)sender
{
    [self.imageArray removeObjectAtIndex:sender.tag];
    [self.imageColletionView reloadData];
}

- (void)loadKeyWordView
{
    
}
#pragma  mark - Custom IBAction
- (IBAction)publicButton:(id)sender {
    if (!self.topicContentTextView.text.length > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"话题内容不能为空" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    [HUD showUIBlockingIndicatorWithText:@"正在发布"];
    int i= 0;
    for (UIImage *pubImage in self.imageArray) {
        NSData *data;
        if (UIImagePNGRepresentation(pubImage).length > 1000000 && UIImagePNGRepresentation(pubImage).length <= 10000000) {
            data = UIImageJPEGRepresentation(pubImage, 0.5);
        }else if (UIImagePNGRepresentation(pubImage).length <= 1000000){
            data = UIImagePNGRepresentation(pubImage);
        }else if (UIImagePNGRepresentation(pubImage).length > 10000000 && UIImagePNGRepresentation(pubImage).length <= 20000000){
            data = UIImageJPEGRepresentation(pubImage, 0.3);
        }else{
            data = UIImageJPEGRepresentation(pubImage, 0.1);
        }
        //图片保存的路径
        //这里将图片放在沙盒的documents文件夹中
        NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        //文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
        [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
        [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:[NSString stringWithFormat:@"/image%d",i]] contents:data attributes:nil];
        //得到选择后沙盒中图片的完整路径
        NSString *filePath = [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  [NSString stringWithFormat:@"/image%d",i]];
        NSLog(@"%@",filePath);
        [self.pathstringArray addObject:filePath];
        i++;
    }
    if (self.pathstringArray.count > 0) {
        NSString *keywordStr = @"";
        for (NSString *keyword in self.keyWordArray) {
            keywordStr = [keywordStr stringByAppendingString:keyword];
            keywordStr = [keywordStr stringByAppendingString:@" "];
        }
        if (keywordStr.length > 0) {
            keywordStr = [keywordStr substringWithRange:NSMakeRange(0, keywordStr.length - 1)];
        }
        
        NSDictionary *params = @{@"content":self.topicContentTextView.text,@"userId":@(self.config.userInfo.id),@"tag":self.tagString,@"keyword":keywordStr};
        NSString *url = [PPAPIList getAPIList].PPAddTopicMsgWithImg;
        [httpRequst POST:url parameters:params imagePathArray:self.pathstringArray imageName:@"image" keyWords:@"img" success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSNumber *processResult = responseObject[@"processResult"];
            if (processResult.boolValue) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTopic" object:nil userInfo:@{@"result":@(1)}];
            }else{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTopic" object:nil userInfo:@{@"result":@(0)}];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTopic" object:nil userInfo:@{@"result":@(2)}];
        }];
        [HUD hideUIBlockingIndicator];
        [self.navigationController popToViewController:self.navigationController.viewControllers[1] animated:YES];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请添加图片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        [HUD hideUIBlockingIndicator];
    }
}

- (IBAction)choseKeyword:(id)sender {
    PPKeyWordsTableViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"PPKeyWordsTableViewController"];
    targetVC.nowArray = self.keyWordArray;
    [self.navigationController pushViewController:targetVC animated:YES];
}
#pragma mark - UICollection datasource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if ([collectionView isEqual:self.imageColletionView]) {
        return self.imageArray.count + 1 ;
    }else{
        return self.keyWordArray.count;
    }
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView isEqual:self.imageColletionView]) {
        PPImageCell *cell = [self.imageColletionView dequeueReusableCellWithReuseIdentifier:@"imageCell" forIndexPath:indexPath];
        if (indexPath.row == self.imageArray.count) {
            [cell.imageShowView setImage:[UIImage imageNamed:@"topicAdd"]];
            cell.deleteButton.hidden = YES;
        }else{
            [cell.imageShowView setImage:[self.imageArray objectAtIndex:indexPath.row]];
            [cell.imageShowView setContentMode:UIViewContentModeScaleAspectFill];
            [cell.imageShowView setClipsToBounds:YES];
            cell.deleteButton.hidden = NO;
            [cell.deleteButton addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
            cell.deleteButton.tag = indexPath.row;
        }
        return cell;
    }else{
        NSString *string = [self.keyWordArray objectAtIndex:indexPath.row];
        PPKeyWordsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"keywordCell" forIndexPath:indexPath];
        [cell.keywordButton setTitle:string forState:UIControlStateNormal];
        return cell;
    }
}
#pragma mark - UICollection delegate
-(void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if ([collectionView isEqual:self.imageColletionView]) {
        if (indexPath.row == self.imageArray.count) {
            [self addPictureButton];
        }
    }
}




#pragma mark - Action Sheet Delegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 2) {
        return;
    }else if (buttonIndex == 1) {
        ELCImagePickerController *elcImagePicker = [[ELCImagePickerController alloc] initImagePicker];
        elcImagePicker.imagePickerDelegate = self;
        elcImagePicker.maximumImagesCount = 9;
        elcImagePicker.onOrder = YES;
        [self.navigationController presentViewController:elcImagePicker animated:YES completion:nil];
    }else if (buttonIndex == 0){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            if (IS_OS_7_OR_LATER) {
                [PPCameraAuthorization getCameraAuthorization];
                if (!self.config.isCameraValid) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请在iPhone的“设置-隐私-相机”选项中，允许程序访问你的相机" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                    [alert show];
                    return;
                }else{
                    [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                }
            }else{
                [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            }
            [self presentViewController:self.imagePicker animated:YES completion:nil];
        }else{
            ELCImagePickerController *elcImagePicker = [[ELCImagePickerController alloc] initImagePicker];
            elcImagePicker.imagePickerDelegate = self;
            elcImagePicker.maximumImagesCount = 9;
            elcImagePicker.onOrder = YES;
            [self.navigationController presentViewController:elcImagePicker animated:YES completion:nil];
        }
    }
}
#pragma mark - ELCImagePickerControllerDelegate
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    for (NSDictionary *dict in info) {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                EYLargePhoto *photo = [[EYLargePhoto alloc] init];
                photo.thumb = [dict objectForKey:UIImagePickerControllerOriginalImage];
                UIImage* image=photo.thumb;
                [self.imageArray addObject:image];
            } else if ([dict objectForKey:UIImagePickerControllerEditedImage]){
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        }
    }
    [picker dismissViewControllerAnimated:YES completion:^{
        [self.imageColletionView reloadData];
    }];
}


- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - UIImagePickControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *myimage = [info valueForKey:UIImagePickerControllerOriginalImage];
    [self.imageArray addObject:myimage];
    [self.imagePicker dismissViewControllerAnimated:YES completion:^{
        [self.imageColletionView reloadData];
    }];
}

#pragma mark - TextView delegate
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.msgLabel.hidden = YES;
    return YES;
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        if (!textView.text.length > 0) {
            self.msgLabel.hidden = NO;
        }else{
            self.msgLabel.hidden = YES;
        }
        return NO;
    }
    return YES;
}


@end
